package com.example.commonutil.util;

import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.Map;

/**
 * YAML配置文件读取工具类
 * 支持从文件路径、resources目录和输入流读取YAML文件，并转换为Java对象或Map
 */
public class YmlLoadUtil {

    // 单例Yaml实例，避免重复创建
    private static final Yaml yaml = new Yaml();

    /**
     * 从文件路径加载YAML并转换为Map
     */
    public static Map<String, Object> loadYamlFromFile(String filePath) throws IOException {
        try (InputStream inputStream = new FileInputStream(new File(filePath))) {
            return loadYamlFromInputStream(inputStream);
        }
    }

    /**
     * 从resources目录加载YAML并转换为Map
     */
    public static Map<String, Object> loadYamlFromResource(String resourcePath) throws IOException {
        try (InputStream inputStream = getResourceStream(resourcePath)) {
            if (inputStream == null) {
                throw new IOException("Resource not found: " + resourcePath);
            }
            return loadYamlFromInputStream(inputStream);
        }
    }

    /**
     * 从输入流加载YAML并转换为Map
     */
    public static Map<String, Object> loadYamlFromInputStream(InputStream inputStream) {
        return yaml.load(inputStream);
    }

    /**
     * 从文件路径加载YAML并转换为指定类型的对象
     */
    public static <T> T loadYamlFromFile(String filePath, Class<T> clazz) throws IOException {
        try (InputStream inputStream = new FileInputStream(new File(filePath))) {
            return loadYamlFromInputStream(inputStream, clazz);
        }
    }

    /**
     * 从resources目录加载YAML并转换为指定类型的对象
     */
    public static <T> T loadYamlFromResource(String resourcePath, Class<T> clazz) throws IOException {
        try (InputStream inputStream = getResourceStream(resourcePath)) {
            if (inputStream == null) {
                throw new IOException("Resource not found: " + resourcePath);
            }
            return loadYamlFromInputStream(inputStream, clazz);
        }
    }

    /**
     * 从输入流加载YAML并转换为指定类型的对象
     */
    public static <T> T loadYamlFromInputStream(InputStream inputStream, Class<T> clazz) {
        return yaml.loadAs(inputStream, clazz);
    }

    /**
     * 将对象转换为YAML字符串
     */
    public static String dumpToYamlString(Object data) {
        return yaml.dump(data);
    }

    /**
     * 获取resources目录下的资源输入流
     */
    private static InputStream getResourceStream(String resourcePath) {
        return YmlLoadUtil.class.getClassLoader().getResourceAsStream(resourcePath);
    }
}